﻿using AppFlat.Common.Jwt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Newtonsoft.Json;


namespace AppFlat.UI.WebApi.Filters
{
    public class AppAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //base.OnAuthorization(actionContext);
            var authHeader2 = from t in actionContext.Request.Headers
                              where t.Key == "auth"
                              select t.Value.FirstOrDefault();
            var token = authHeader2.FirstOrDefault();

            if (token==null)   // 没有登录
                actionContext.Response= actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("token 空"));
            var result = JwtHelper.JieM(token); // 解密Token
            switch(result)
            {
                case "Token has expired":
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("身份已过期"));
                    break;
                case "Token has invalid signature":
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("身份可能被篡改！"));
                    break;
                case "other error":
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("服务器在验证身份时出错！"));
                    break;
            }
            // 解密成功，在验证是否有当前权限
            var userInfo= JsonConvert.DeserializeObject<JwtUserInfo>(result);
            /*
            List<Action> list = HttpContext.Current.Cache.Get("角色名");

            if (list == null)
            {
                //根据用户角色 查询拥有的权限
                //  list= 查询的结果
                // 将角色权限进行缓存
               // HttpContext.Current.Cache.Insert("RoleName",list); // 缓存
            }
            
            // 和当前controller、action、method进行匹配
            //if ( list.Any(action=>action.Method==""))
            // 如果匹配不成功，  actionContext.Response=

            // 如果匹配成功， 将用户信息 放置RouteData中
            actionContext.RequestContext.RouteData.Values.Add("user", userInfo);
            */
        }
    }
}